<template>
  <div>
    <div class="boxs">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item label="" prop="name">
          <el-input
            v-model="ruleForm.name"
            type="text"
            autocomplete="off"
            placeholder="账号"
          />
        </el-form-item>
        <el-form-item label="" prop="pwd">
          <el-input
            v-model="ruleForm.pwd"
            type="password"
            autocomplete="off"
            placeholder="密码"
          />
        </el-form-item>
        <p class="zhuce"><a href="/register">还没有账号，立即注册</a></p>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
  
  <script lang="ts" setup>
import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { login } from "../../api/MenuApi";
import { useRouter } from "vue-router";

const router = useRouter();

const ruleFormRef = ref<FormInstance>();

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入用户名"));
  } else {
    if (ruleForm.name !== "") {
      if (!ruleFormRef.value) return;
    }
    callback();
  }
};
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入密码"));
  } else if (value !== ruleForm.pwd) {
    callback(new Error("Two inputs don't match!"));
  } else {
    callback();
  }
};

// 表单数据
const ruleForm = reactive({
  name: "",
  pwd: "",
});

const rules = reactive<FormRules>({
  name: [{ validator: validatePass, trigger: "blur" }],
  pwd: [{ validator: validatePass2, trigger: "blur" }],
});

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid: any) => {
    if (valid) {
      login(ruleForm).then((res) => {
        if (res.data.code == 1) {
          localStorage.setItem("token", res.data.token);
          localStorage.setItem("uid", res.data.data[0].id);
          router.push("/index");
        }
      });
    } else {
      console.log("error submit!");
      return false;
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>
<style scoped>
.boxs {
  width: 500px;
  height: 200px;
  /* border: 1px solid #ccc; */
  position: fixed;
  top: calc(50% - 100px);
  left: calc(50% - 280px);
}
.el-button,
.el-input {
  width: 400px;
  height: 40px;
}
.zhuce {
  text-align: right;
  color: #409eff;
}
a {
  color: #409eff;
  text-decoration: none;
}
</style>